// index.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data:{
    novelList:[],
    comicList:[],
    videoList:[],
    searchList:[],
    words:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(){
    if(!wx.getStorageSync('login-token')){
      wx.redirectTo({
        url: '/pages/login/login'
      })
    }
    this.getData()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onRefresh()
  },
  //刷新
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...',
    })
    this.getData();
  },
  //网络请求，获取数据
  getData(){
    app.$http.get('/app/collection/list', {pageNum:1,pageSize:6,mediaType:0,views:1}).then(res =>{
      this.setData({novelList:res.data.records})
      app.$http.get('/app/collection/list', {pageNum:1,pageSize:6,mediaType:1,views:1}).then(res =>{
        this.setData({comicList:res.data.records})
        app.$http.get('/app/collection/list', {pageNum:1,pageSize:6,mediaType:2,views:1}).then(res =>{
          this.setData({videoList:res.data.records})
          //隐藏loading 提示框
          wx.hideLoading();
          //隐藏导航条加载动画
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        })
      })
    }).catch(err => {
      console.log(err)
    })
  },
  onInput: function(e){
    if(e.detail.value != ""){
      this.setData({words:e.detail.value})
      wx.setStorageSync('words', this.data.words)
      app.$http.get('/app/collection/list', {pageNum:1,pageSize:5,mediaTitle:e.detail.value}).then(res => {
        this.setData({searchList:res.data.records})
      })
    }else{
      this.setData({searchList:[]})
    }
  },
  onBlur(){
    this.setData({searchList:[]})
  },
  toCollection: function(e){
    const collection = e.currentTarget.dataset.item;
    wx.setStorageSync('collection', collection)
    wx.navigateTo({
      url: '/pages/index/collection/collection',
    })
  },
  toSearch: function(e){
    wx.navigateTo({
      url: '/pages/index/search/search',
    })
  },
  toMore: function(e){
    const id = e.currentTarget.dataset.id
    let url = ''
    switch (id){
      case '0':
        url = '/pages/mediaList/mediaList?mediaType=0&type=0'
        break;
      case '1':
        url = '/pages/mediaList/mediaList?mediaType=1&type=0'
        break;
      case '2':
        url = '/pages/mediaList/mediaList?mediaType=2&type=0'
        break;
    }
    wx.navigateTo({url})
  },
  onShow(){
    this.getData()
  }
})
